#include "dmatrix.h"

typedef struct {
    memcached_st *mc;
} DMatrix;


DMatrix *dmatrix_create(void) {
    DMatrix *dm;
    dm = g_slice_new(DMatrix);
    dm->mc = g_slice_new(memcached_st);
    memcached_create(dm->mc);
    return dm;
}

void dmatrix_add_server(DMatrix *dm, const char *host, int port) {
    int ret = memcached_server_add(dm->mc, host, port);
    assert(ret==0);
}

void dmatrix_free(DMatrix *dm) {
    memcached_free(dm->mc);
    g_slice_free(memcached_st, dm->mc);
    g_slice_free(DMatrix, dm);
}

void dmatrix_set(DMatrix *dm, int x, int y, int val) {
    char *key_str = NULL;
    char *val_str = NULL;
    int ret = 0;
    key_str = g_strdup_printf("%i@%i", x, y);
    val_str = g_strdup_printf("%i", val);

    ret = memcached_set(dm->mc, key_str, strlen(key_str),
                                val_str, strlen(val_str),
                        (time_t)0, (uint32_t)0);
    assert(ret==0);
    g_free(val_str);
    g_free(key_str);
}

int dmatrix_get(DMatrix *dm, int x, int y) {
    char *val_str = NULL;
    char *key_str = NULL;
    size_t val_len;
    uint32_t flags = 0;
    memcached_return rc;
    int ret = 0;

    key_str = g_strdup_printf("%i@%i", x, y);
    val_str = memcached_get(dm->mc, key_str, strlen(key_str),
                                    &val_len, &flags, &rc);
    assert(rc==0);

    sscanf(val_str, "%d", &ret);
    g_free(key_str);
    free(val_str);
    return ret;
}


int main(void) {
    int i, j, v;
    DMatrix *dm = dmatrix_create();
    dmatrix_add_server(dm, "127.0.0.1", 6666);

    for(i=0; i<=100; i++) {
        for(j=0; j<=1000; j++) {
            v = dmatrix_get(dm, i, j);
            //dmatrix_set(dm, i, j, 123);
        }
    }



    dmatrix_free(dm);




    return EXIT_SUCCESS;
}



